<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\dkgzh\controller;

use cmf\controller\HomeBaseController;
use app\daikuan\model\DriverLoanModel;
use app\daikuan\model\DriverReimModel;
use app\daikuan\model\DriverInterestModel;
use think\Db;

class HuankuanController extends HomeBaseController {

    /**
     * Description of HuankuanController
     *
     * @author PVer
     */
    //待还款
    public function dhkzd() {
        $user = cmf_get_current_user();
        $map = array();
        $map['b.user_category'] = 1;
        $map['b.dk_status'] = 1;
        $map["a.DriverId"] = $user["id"];
        $map["a.IsYQ"] = 0;
        $map["a.Status"] = 3;
        $list = db('driver_loan a')->join(array(array('dk_user b', 'a.DriverId=b.id ', 'LEFT')
                ))
                ->field('a.*,b.mobile,b.user_nickname,DATEDIFF(now(),a.RepayMentDateTime)  diffday')
                ->where($map)
                ->paginate();
        $new_list = array();
        $driverInterestModel = new DriverInterestModel();
        $interes = $driverInterestModel->get(1);
        $yq = $interes['overdueInterest'];
        $overdueDay = $interes['overdueDay'];
        foreach ($list as $row) {
            $diffday = $row['diffday'];
            $lixi = 0;
            if ($diffday > 0) {
                $zq = ceil($diffday / $overdueDay);
                $lixi = $yq * $zq * $row['ApplyAmount'] / 100;
                //$lixi = $yq . '-' . $zq . '-' . $row['ApplyAmount'] . '-' . $lixi;
                $row['lixi'] = $lixi;
            } else {
                $row['diffday'] = 0;
                $row['lixi'] = 0;
            }
            $d_map['Flag']=0;
            $d_map['LoanId']= $row['Id'] ;
            $drz=Db::name('driver_reim')->where($d_map)->field('sum(ReimAmount) as drz')->find();
            $row['drz_monay'] = $drz['drz'];
            $new_list[] = $row;
        }

        $this->assign('list', $new_list);
        return $this->fetch();
    }

//立即还款
    public function dhkzdljhk() {
        $id = input('id');
        $map = array();
        $map["a.Id"] = $id;
        $driverLoanModel = new DriverLoanModel();
        $info = db('driver_loan a')->join(array(array('dk_user b', 'a.DriverId=b.id ', 'LEFT')
                ))
                ->field('a.*,b.mobile,b.user_nickname,DATEDIFF(now(),a.RepayMentDateTime)  diffday')
                ->where($map)
                ->find();
        $driverInterestModel = new DriverInterestModel();
        $interes = $driverInterestModel->get(1);
        $yq = $interes['overdueInterest'];
        $overdueDay = $interes['overdueDay'];
        $diffday = $info['diffday'];
        $lixi = 0;
        if ($diffday > 0) {
            $zq = ceil($diffday / $overdueDay);
            $lixi = $yq * $zq * $info['ApplyAmount'] / 100;
            //$lixi = $yq . '-' . $zq . '-' . $row['ApplyAmount'] . '-' . $lixi;
            $lixi = sprintf("%.2f",$lixi);
            $info['lixi'] = $lixi;
        } else {
            $info['diffday'] = 0;
            $info['lixi'] = 0;
        }




        $this->assign('info', $info);
        return $this->fetch();
    }

//上传还款凭证
    public function pzscsb() {
        return $this->fetch();
    }

//还款记录 全部信息
    public function hkjl1() {
        $id = cmf_get_current_user_id();
        $map = array();
        $map['b.user_category'] = 1;
        $map['b.dk_status'] = 1;
        $map["a.UserId"] = $id;
        $driverReimModel = new DriverReimModel();
        $list = db('driver_reim a')->join(array(array('dk_user b', 'a.UserId=b.id ', 'LEFT'),
                    array('dk_driver_loan c', 'a.LoanId=c.Id', 'INNER'),
                ))
                ->field('a.*,b.mobile,b.user_nickname,c.ApplyAmount,c.Reimbursement,c.ReimAmount CReimAmount,c.Id loanid,c.ApplyDateLength,c.CargoCode,c.ApplyDate,c.RepayMentDateTime,c.IsYQ')
                ->where($map)
                ->select();
		$list = $list->toArray();

        foreach ($list as $key=>&$value){
            if($value['Flag'] ==0){
                $value['Flag_txt'] = "审核中";
            }else if($value['Flag']==1){
                $value['Flag_txt'] = "已审核";
            }else if($value['Flag']==2){
                $value['Flag_txt'] = "拒绝审核";
            }
        }

        $this->assign('list', $list);
        return $this->fetch();
    }

    //还款记录已还清
    public function hkjl2() {
        $map = array();
        $id = cmf_get_current_user_id();
        $map['b.user_category'] = 1;
        $map['b.dk_status'] = 1;
        $map["a.UserId"] = $id;
        $map['c.Status'] = 4;
        $map['a.Flag'] = 1;
        //$map["c.IsYQ"] = 1;
        $driverReimModel = new DriverReimModel();
        $list = db('driver_reim a')->join(array(array('dk_user b', 'a.UserId=b.id ', 'LEFT'),
                    array('dk_driver_loan c', 'a.LoanId=c.Id', 'INNER'),
                ))
                ->field('a.*,b.mobile,b.user_nickname,c.ApplyAmount,c.Reimbursement,c.ReimAmount CReimAmount,c.Id loanid,c.ApplyDateLength,c.CargoCode,c.ApplyDate,c.RepayMentDateTime,c.IsYQ')
                ->where($map)
                ->select();
        $this->assign('list', $list);
        return $this->fetch();
    }

    //还款记录 未还清
    public function hkjl3() {
        $map = array();
        $id = cmf_get_current_user_id();
        $map['b.user_category'] = 1;
        $map['b.dk_status'] = 1;
        $map["a.DriverId"] = $id;
       // $map["a.IsYQ"] = 0;
        $map['a.Status'] = 3;
        $driverReimModel = new DriverReimModel();
        $list =db('driver_loan a')->join(array(array('dk_user b', 'a.DriverId=b.id ', 'LEFT')
        ))
            ->field('a.*,b.mobile,b.user_nickname,DATEDIFF(now(),a.RepayMentDateTime)  diffday')
            ->where($map)
            ->select();
        $this->assign('list', $list);
        return $this->fetch();
    }

    //还款记录 审核未通过
    public function hkjl4() {
        $map = array();
        $id = cmf_get_current_user_id();
        $map['b.user_category'] = 1;
        $map['b.dk_status'] = 1;
        $map["a.UserId"] = $id;
        $map["c.IsYQ"] = 0;
        $driverReimModel = new DriverReimModel();
        $list = db('driver_reim a')->join(array(array('dk_user b', 'a.UserId=b.id ', 'LEFT'),
            array('dk_driver_loan c', 'a.LoanId=c.Id', 'INNER'),
        ))
            ->field('a.*,b.mobile,b.user_nickname,c.ApplyAmount,c.Reimbursement,c.ReimAmount CReimAmount,c.Id loanid,c.ApplyDateLength,c.CargoCode,c.ApplyDate,c.RepayMentDateTime,c.IsYQ')
            ->where($map)
            ->select();
        $this->assign('list', $list);
        return $this->fetch();
    }

    public function postHuankuan() {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $driverReimModel = new DriverReimModel();
            $user = cmf_get_current_user();
            $this->assign('info', $user);
            $arr = array();
            if(!$data['thisAmount']){
                $this->error("还款金额不能为0");
            }
            $arr['ReimAmount'] = $data['thisAmount'];
            $arr['UserId'] = $user["id"];
            $arr['Creattime'] = date("Y-m-d H:i:s");
            $arr['LoanId'] = $data['id'];
            $arr['pingzheng'] = $data['imgid1'];

            $result = $driverReimModel->save($arr);
            if ($result !== false) {
                $this->success("操作成功", url("dhkzd"));
            } else {
                $this->error("操作失败");
            }
        } else {
            $this->error("请求错误");
            return $this->fetch(':zcym');
        }
    }

//上传图片
    public function upload() {
        $files = array();
        $success = 0;    //用户统计有多少张图片上传成功了

        foreach ($_FILES as $item) {
            $index = count($files);
            $files[$index]['srcName'] = $item['name'];    //上传图片的原名字
            $files[$index]['error'] = $item['error'];    //和该文件上传相关的错误代码
            $files[$index]['size'] = $item['size'];        //已上传文件的大小，单位为字节
            $files[$index]['type'] = $item['type'];        //文件的 MIME 类型，需要浏览器提供该信息的支持，例如"image/gif"
            $files[$index]['success'] = false;            //这个用于标志该图片是否上传成功
            $files[$index]['path'] = '';                //存图片路径
            // 接收过程有没有错误
            if ($item['error'] != 0)
                continue;
            //判断图片能不能上传
            if (!is_uploaded_file($item['tmp_name'])) {
                $files[$index]['error'] = 8000;
                continue;
            }
            //扩展名
            $extension = '';
            if (strcmp($item['type'], 'image/jpeg') == 0) {
                $extension = '.jpg';
            } else if (strcmp($item['type'], 'image/png') == 0) {
                $extension = '.png';
            } else if (strcmp($item['type'], 'image/gif') == 0) {
                $extension = '.gif';
            } else {
                //如果type不是以上三者，我们就从图片原名称里面去截取判断去取得(处于严谨性)    
                $substr = strrchr($item['name'], '.');
                if (FALSE == $substr) {
                    $files[$index]['error'] = 8002;
                    continue;
                }

                //取得元名字的扩展名后，再通过扩展名去给type赋上对应的值
                if (strcasecmp($substr, '.jpg') == 0 || strcasecmp($substr, '.jpeg') == 0 || strcasecmp($substr, '.jfif') == 0 || strcasecmp($substr, '.jpe') == 0) {
                    $files[$index]['type'] = 'image/jpeg';
                } else if (strcasecmp($substr, '.png') == 0) {
                    $files[$index]['type'] = 'image/png';
                } else if (strcasecmp($substr, '.gif') == 0) {
                    $files[$index]['type'] = 'image/gif';
                } else {
                    $files[$index]['error'] = 8003;
                    continue;
                }
                $extension = $substr;
            }

            //对临时文件名加密，用于后面生成复杂的新文件名
            $md5 = md5_file($item['tmp_name']);
//        //取得图片的大小
            $imageInfo = getimagesize($item['tmp_name']);
            $rawImageWidth = $imageInfo[0];
            $rawImageHeight = $imageInfo[1];
            $path = UPLOAD_ROOT . '/upload/' . date('Ymd') . '/';
            $url = '/upload/' . date('Ymd') . '/';
            if (!file_exists($path)) {
                mkdir($dir, 0766, true);
                chmod($dir, 0766);
                chmod($dir, 0777);
            } else if (!is_writable($path)) {
                chmod($dir, 0766);
                chmod($dir, 0777);
                if (!is_writable($dir)) {
                    throw new FileSystemException("目录 $dir 不可写");
                }
            }
            $name = "$md5.0x{$rawImageWidth}x{$rawImageHeight}{$extension}";
            $ret = file_exists($path . $name) ? true : move_uploaded_file($item['tmp_name'], $path . $name);
            if ($ret === false) {
                $files[$index]['error'] = 8004;
                continue;
            } else {
                $files[$index]['path'] = $url . $name;     //存图片路径
                $files[$index]['success'] = true;            //图片上传成功标志
                $files[$index]['width'] = $rawImageWidth;    //图片宽度
                $files[$index]['height'] = $rawImageHeight;    //图片高度
                $success ++;    //成功+1
            }
        }
//将图片已json形式返回给js处理页面  ，这里大家可以改成自己的json返回处理代码
        echo json_encode(array(
            'total' => count($files),
            'success' => $success,
            'files' => $files,
        ));
    }

//这里我附上ensure_writable_dir()函数的代码
    /**
     * 确保文件夹存在并可写
     *
     * @param string $dir
     */
    function ensure_writable_dir($dir) {

        if (!file_exists($dir)) {
            mkdir($dir, 0766, true);
            chmod($dir, 0766);
            chmod($dir, 0777);
        } else if (!is_writable($dir)) {
            chmod($dir, 0766);
            chmod($dir, 0777);
            if (!is_writable($dir)) {
                throw new FileSystemException("目录 $dir 不可写");
            }
        }
    }

}
